const mqtt = require('mqtt')
const protocol = 'ws'
const host = '106.13.74.173'
const port = 8083
const endpoint = '/mqtt'
const mqttUrl = `${protocol}://${host}:${port}${endpoint}`

const userOptions = {
  username: 'raspberry',
  password: '123456'
}

const client = mqtt.connect(mqttUrl, userOptions)

client.on('connect', () => {
  console.log('Connection succeeded!')
})
client.on('error', error => {
  console.log('Connection failed', error)
})

const number = 10002
const cropName = '香蕉'
const subTopic = `device/${number}`

// 1. 发布自身及待控制设备的信息
const id = setInterval(() => {
  const pubTopic = `user/${number}`
  const param = {
    number, cropName, subTopic
  }
  console.log('发布用户信息', param)
  client.publish(pubTopic, JSON.stringify(param), { qos: 2 })
}, 5000)

// 2. 订阅，当收到目标订阅的回复，终止过程1
client.on('message', (topic, message) => {
  try {
    const { temp, hum, light } = JSON.parse(message.toString())
    console.log('开始获取数据', temp, hum, light)
    clearInterval(id)
  } catch (e) {
    console.log('主题', topic, '消息', message)
  }
})
client.subscribe(subTopic, { qos: 2 })

